package com.wisemoresystem.seal.util.http;


import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.util.*;

public class HttpTools {

    public static CloseableHttpClient client = HttpClients.createDefault();

    public static String get(String url) {
        System.err.println("请求url-->" + url);
        String strGetResponseBody = "";

        HttpGet get = new HttpGet(url);

        try {
            HttpResponse response = client.execute(get);
            System.err.println("状态-->" + response.getStatusLine());

            HttpEntity entity = response.getEntity();
            if (null != entity) {
                strGetResponseBody = EntityUtils.toString(entity);

                EntityUtils.consume(entity);
            }

        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
//            try {
//                client.close();
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
        }

        return strGetResponseBody;

    }

    public static String post(String url, Map<String, Object> map) {
        CloseableHttpClient client = HttpClients.createDefault();

        String strPostResponseBody = "";
        HttpPost post = new HttpPost(url);
        List<NameValuePair> ListParams = new ArrayList<NameValuePair>();
        Set<String> keys = map.keySet();
        for (String key : keys) {
            ListParams.add(new BasicNameValuePair(key, map.get(key) + ""));
        }

        try {
            post.setEntity(new UrlEncodedFormEntity(ListParams));
            HttpResponse response = client.execute(post);
            HttpEntity entity = response.getEntity();
            if (null != entity) {
                strPostResponseBody = EntityUtils.toString(entity);


                EntityUtils.consume(entity);
            }

        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
//            try {
//                client.close();
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
        }

        return strPostResponseBody;

    }

    public static void main(String[] args) {
        String url = "http://oa.epkoko.com";
        Map<String, String> map = new HashMap<String, String>();
        map.put("a", "aaa");
        map.put("b", "vbvv");
        System.err.println(get(url));
    }
}
